package container

import (
	v1 "container-management/api/container/v1"
	"container-management/internal/consts"
	"container-management/internal/dao"
	"container-management/internal/service"
	"container-management/utility/docker"
	"context"
	"errors"
	"github.com/docker/docker/api/types/image"
	"github.com/docker/docker/client"
)

type sContainer struct{}

func New() *sContainer {
	return &sContainer{}
}

func init() {
	service.RegisterContainer(New())
}

func (s *sContainer) CreateContainer(ctx context.Context, req *v1.CreateContainerReq) error {
	client, err := docker.NewDockerClient()
	if err != nil {
		return err
	}
	defer client.Close()
	newContainer, _ := client.ContainerInspect(ctx, req.Name)
	if newContainer.ContainerJSONBase != nil {
		return errors.New(consts.ErrContainerName)
	}
	record, err := dao.GetImageIdByName(ctx, req.Image)
	if err != nil || record.IsEmpty() {
		return errors.New(consts.ErrImageNotExist)
	}
	imageInfo, err := client.ImageInspect(ctx, req.Image)
	if err != nil {
		return err
	}
	if len(req.Entrypoint) == 0 {
		req.Entrypoint = imageInfo.Config.Entrypoint
	}
	if len(req.Cmd) == 0 {
		req.Cmd = imageInfo.Config.Cmd
	}
	return nil
}

func checkImageExist(client *client.Client, imageItem string) bool {
	images, err := client.ImageList(context.Background(), image.ListOptions{})
	if err != nil {
		return false
	}
	for _, img := range images {
		for _, tag := range img.RepoTags {
			if tag == imageItem || tag == imageItem+":latest" {
				return true
			}
		}
	}
	return false
}
